package com.ruoyi.business.ocpxController;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("ownOCPXApi")
public class OcpxController {

    @Autowired
    private RedisCache redisCache;

    private final static String CLASSESEN = "ocpx";

    private final static String SECRET = "51bce62df4df5a1e1f7f2775b5c3712e";

    private final static String ACCESS_ID = "tp2bf48e40211a102e861888c0709833aa";


    @Log(title = "OCPX", businessType = BusinessType.ESCALATION, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");


        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }


        Map<String, Object> requiredParameters = new HashMap<>();
        requiredParameters.put("imei", baseParamsMap.get("imei"));
        requiredParameters.put("imei_md5", baseParamsMap.get("imei_md5"));
        requiredParameters.put("oaid", baseParamsMap.get("oaid"));
        requiredParameters.put("oaid_md5", baseParamsMap.get("oaid_md5"));
        requiredParameters.put("android_id_md5", baseParamsMap.get("android_id_md5"));
        requiredParameters.put("mac_md5", baseParamsMap.get("mac_md5"));
        requiredParameters.put("idfa", baseParamsMap.get("idfa"));
        requiredParameters.put("request_id", IdUtils.fastSimpleUUID());
        requiredParameters.put("os", 0);
        requiredParameters.put("ts", (System.currentTimeMillis()/1000)+"");

        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
            requiredParameters.put("ua", baseParamsMap.get("ua") + "");
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
            requiredParameters.put("ip", ip);
        }else{
            ip = null;
        }

        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        requiredParameters.putAll(staticParamsMap);


        String callbackUrl = baseParamsMap.get("callback_url") + "";
        requiredParameters.put("callback_url", URLEncoder.encode(callbackUrl, Constants.UTF8));
        String signature =  DigestUtils.md5DigestAsHex(("access_id="+requiredParameters.get("access_id")+"&ts="+requiredParameters.get("ts") + SECRET).getBytes(Constants.UTF8)).toLowerCase();
        requiredParameters.put("signature", signature);

        List<String> tempList = new ArrayList<>();
        for(String key: requiredParameters.keySet()){
            tempList.add(key+"="+requiredParameters.get(key));
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            return reportResults==null?"":reportResults;
        }catch (Exception e){
            e.printStackTrace();
        }
        return reportResultsStr;
    }

    @Log(title = "OCPX", businessType = BusinessType.CALLBACK, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object send(HttpServletRequest request, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);
        String resultStr = HttpUtils.sendGet(requestAddress, queryString);
        try {
            JSONObject resultJson = JSON.parseObject(resultStr);
            return resultJson==null?"":resultJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }



}
